package com.example.devinfan.criminalintent.Fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.example.devinfan.criminalintent.Activity.CrimeCameraActivity;
import com.example.devinfan.criminalintent.Activity.CrimeListActivity;
import com.example.devinfan.criminalintent.Activity.CrimePagerActivity;
import com.example.devinfan.criminalintent.model.Crime;
import com.example.devinfan.criminalintent.model.CrimeLab;
import com.example.devinfan.criminalintent.R;
import com.example.devinfan.criminalintent.model.Photo;
import com.example.devinfan.criminalintent.model.PictrueUtils;

import java.io.File;
import java.util.Date;
import java.util.UUID;

public class CrimeFragment extends Fragment {
    private Crime mCrime;
    private EditText mTitleField;
    private Button mDateButton;
    private CheckBox mSolvedCheckBox;
    private ImageButton mPhotoButton;
    private ImageView mPhotoView;
    private Button mReportButton;
    private Button mSuspectButton;

    public static final String EXTRA_CRIME_ID = "com.example.devinfan.criminalintent.crime_id";
    private static final String DIALOG_DATE = "date";
    private static final int REQUEST_DATE = 0;
    private static final int REQUEST_PHOTO = 1;
    private static final int REQUEST_CONTACT = 2;
    private static final String TAG = "CrimeFragment";
    private static final String DIALOG_IMAGE = "image";
    @Override
    public void onCreate(Bundle saveInstanceState){
        super.onCreate(saveInstanceState);
        setHasOptionsMenu(true);
        UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID);
        mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater,ViewGroup parent,Bundle saveInstanceState){
        final View view = inflater.inflate(R.layout.fragment_crime,parent,false);

        mTitleField = (EditText)view.findViewById(R.id.crime_title);
        mDateButton = (Button)view.findViewById(R.id.crime_date);
        mSolvedCheckBox = (CheckBox)view.findViewById(R.id.crime_solved);
        mPhotoButton = (ImageButton)view.findViewById(R.id.crime_imageButton);
        mPhotoView = (ImageView)view.findViewById(R.id.crime_imageView);
        mReportButton = (Button)view.findViewById(R.id.crime_reportButton);
        mSuspectButton = (Button)view.findViewById(R.id.crime_suspectButton);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
            if (NavUtils.getParentActivityName(getActivity()) != null && getActivity().getActionBar() != null){
                    getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
            }
        }

        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
                    registerForContextMenu(view);
                }else {
                    getActivity().startActionMode(new ActionMode.Callback() {
                        @Override
                        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                            MenuInflater menuInflater = mode.getMenuInflater();
                            menuInflater.inflate(R.menu.crime_item_context,menu);
                            return true;
                        }

                        @Override
                        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                            return false;
                        }

                        @Override
                        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                            switch (item.getItemId()){
                                case R.id.menu_item_delete_crime:
                                    CrimeLab.get(getActivity()).deleteCrime(mCrime);
                                    if(mCrime.getPhoto() != null){
                                        String filename = mCrime.getPhoto().getFilename();
                                        if(filename != null){
                                            deleteImageFile(filename);
                                            CrimeLab.get(getActivity()).deleteCrime(mCrime);
                                        }
                                    }
                                    mode.finish();
                                    startCrimeListActivity();
                                    return true;
                                default:
                                    return false;
                            }
                        }

                        @Override
                        public void onDestroyActionMode(ActionMode mode) {

                        }
                    });
                }
                return true;
            }
        });

        mTitleField.setText(mCrime.getTitle());
        mTitleField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //this space intentionally left blank
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mCrime.setTitle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                //this one too
            }
        });

        updateDate();
        mDateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getActivity().getSupportFragmentManager();
                ChangeTimeFragment dialog = ChangeTimeFragment.newInstance(mCrime.getDate());
                dialog.setTargetFragment(CrimeFragment.this,REQUEST_DATE);
                dialog.show(fm,DIALOG_DATE);
            }
        });

        mSolvedCheckBox.setChecked(mCrime.isSolved());
        mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //Set the crime's solved property
                mCrime.setSolved(isChecked);
                mDateButton.setEnabled(isChecked);
            }
        });

        //If camera is not available ,disable camera functionality
        PackageManager pm = getActivity().getPackageManager();
        Boolean hasACamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) ||
                pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT) ||
                Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD ||
                Camera.getNumberOfCameras() > 0;
        if(!hasACamera) mPhotoButton.setEnabled(false);

        mPhotoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), CrimeCameraActivity.class);
                startActivityForResult(i,REQUEST_PHOTO);
            }
        });

        mPhotoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Photo p = mCrime.getPhoto();
                if(p == null) return ;
                FragmentManager fm = getActivity().getSupportFragmentManager();
                String path = getActivity().getFileStreamPath(p.getFilename()).getAbsolutePath();
                ImageFragment.newInstance(path).show(fm,DIALOG_IMAGE);
            }
        });

        mReportButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, getCrimeReport());
                intent.putExtra(Intent.EXTRA_SUBJECT,getString(R.string.crime_report_subject));
                intent = Intent.createChooser(intent,getString(R.string.send_report));
                startActivity(intent);
            }
        });

        mSuspectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent,REQUEST_CONTACT);
            }
        });

        if (mCrime.getSuspect() != null){
            mSuspectButton.setText(mCrime.getSuspect());
        }

        return view;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo){
        getActivity().getMenuInflater().inflate(R.menu.crime_item_context,menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item){
        switch (item.getItemId()) {
            case R.id.menu_item_delete_crime:
                CrimeLab.get(getActivity()).deleteCrime(mCrime);
                startCrimeListActivity();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case android.R.id.home:
                if (NavUtils.getParentActivityName(getActivity())!=null){
                    NavUtils.navigateUpFromSameTask(getActivity());
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onStart(){
        super.onStart();
        showPhoto();
    }

    @Override
    public void onPause(){
        super.onPause();
        CrimeLab.get(getActivity()).saveCrimes();
    }

    @Override
    public void onStop(){
        super.onStop();
        PictrueUtils.cleanImageView(mPhotoView);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        if (resultCode != Activity.RESULT_OK)return ;
        if (requestCode == REQUEST_DATE){
            Date date = (Date)data.getSerializableExtra(ChangeTimeFragment.EXTRA_CHANGE_DATE);
            mCrime.setDate(date);
            updateDate();
        }else if(requestCode == REQUEST_PHOTO){
            if(mCrime.getPhoto() != null){
                String filename = mCrime.getPhoto().getFilename();
                if(filename != null){
                    deleteImageFile(filename);
                }
            }
            //Create a new Photo object and attach it to the crime
            Photo photo = (Photo)data.getSerializableExtra(CrimeCameraFragment.EXTRA_PHOTO);
            String filename = photo.getFilename();
            if(filename != null){
                mCrime.setPhoto(photo);
                showPhoto();
            }
        }else if(requestCode == REQUEST_CONTACT){
            Uri contactUri = data.getData();

            //Specify which fields you want your query to return
            //values for.
            String[] queryFields = new String[]{
              ContactsContract.Contacts.DISPLAY_NAME
            };
            //Perform your query - the contactUri is like a "where"
            //clause here
            Cursor c = getActivity().getContentResolver().query(contactUri,queryFields,null,null,null);
            //Double-check that you actually got results
            if (c.getCount() == 0){
                c.close();
                return ;
            }

            //Pull out the first column of the first row of data
            //that is your suspect's name
            c.moveToFirst();
            String suspect = c.getString(0);
            mCrime.setSuspect(suspect);
            mSuspectButton.setText(suspect);
            c.close();
        }
    }

    private void startCrimeListActivity(){
        CrimePagerActivity.mCrimePagerAdapter.notifyDataSetChanged();
        Intent intent = new Intent(getActivity(), CrimeListActivity.class);
        startActivity(intent);
    }

    //删除已有的图片
    private void deleteImageFile(String filename){
        Crime crime  = mCrime;
        CrimeLab.get(getActivity()).deleteCrime(crime);
        mCrime.setPhoto(new Photo());
        CrimeLab.get(getActivity()).addCrime(mCrime);
        File deleteFile = new File(getActivity().getFileStreamPath(filename).getAbsolutePath());
        PictrueUtils.deleteImageFile(deleteFile);
    }

    private void showPhoto(){
        //(Re)set the image button's image based on our photo
        Photo p = mCrime.getPhoto();
        BitmapDrawable b = null;
        if (p != null) {
            String path = getActivity().getFileStreamPath(p.getFilename()).getAbsolutePath();
            b = PictrueUtils.getScaledDrawable(getActivity(),path);
        }
        mPhotoView.setImageDrawable(b);
    }

    private String getCrimeReport(){
        String solvedString;
        if(mCrime.isSolved()){
            solvedString = getString(R.string.crime_report_solved);
        }else{
            solvedString = getString(R.string.crime_report_unsolved);
        }
        String dateFormat = "EEE, MMM dd";
        String dateString = android.text.format.DateFormat.format(dateFormat,mCrime.getDate()).toString();

        String suspect = mCrime.getSuspect();
        if (suspect == null){
            suspect = getString(R.string.crime_report_no_suspect);
        }else {
            suspect = getString(R.string.crime_report_suspect,suspect);
        }

        String report = getString(R.string.crime_report,mCrime.getTitle(),dateString,solvedString,suspect);

        return report;
    }

    public static CrimeFragment newInstance(UUID crimeId){
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_CRIME_ID,crimeId);

        CrimeFragment fragment = new CrimeFragment();
        fragment.setArguments(args);

        return fragment;
    }

    private void updateDate(){
        mDateButton.setText(mCrime.getDate().toString());
    }
}
